package gov.nist.healthcare.testframework.client;

import gov.nist.healthcare.core.MalformedMessageException;
import gov.nist.healthcare.core.message.v2.er7.Er7Message;
import gov.nist.healthcare.testframework.communication.MllpUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

    public static void main(String[] args) throws UnknownHostException,
            IOException, MalformedMessageException {
        // Send a message
        Socket client = new Socket("localhost", 9000);
        client.setSoTimeout(60000);
        // OutputStream out = client.getOutputStream();
        String message = "MSH|^~\\&|NIST_GENERIC_SENDER|NIST_GENERIC_SENDER|NIST_GENERIC|NIST_GENERIC|20090810141748||ADT^A04^ADT_A01|Flame-990001|P|2.3.1\n"
                + "EVN|A04|20090810\n"
                + "PID|||100^^^domain1&1.2.3.4.5.1000&ISO^PI||MOORE^CHIP|Barnes|19840711|M|||^^Montreal^^||||||||153-12-5100\n"
                + "PV1||V\n";
        PrintWriter out = new PrintWriter(client.getOutputStream(), true);
        out.println(MllpUtils.wrapMessage(new Er7Message(message)));
        out.flush();
        System.out.println(client.isClosed());
        try {
            for (;;) {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));
                String line = in.readLine();
                if (line != null) {
                    System.out.println(line);
                } else {
                    break;
                }
            }
        }
        // Exception thrown when network timeout occurs
        catch (InterruptedIOException iioe) {
            System.err.println("Remote host timed out during read operation");
        }
        // Exception thrown when general
        // network I/O error occurs
        catch (IOException ioe) {
            System.err.println("Network I/O error - " + ioe);
        }
        out.close();
    }
}
